package main

import (
	"context"
	"fmt"
	"gin-gateway/example/gateway_demo/otherProxy/public"
	"gin-gateway/example/gateway_demo/otherProxy/tcp_middleware"
	"net"
	"time"
	"gin-gateway/example/gateway_demo/otherProxy/load_balance"
	"gin-gateway/example/gateway_demo/otherProxy/tcp_proxy"
)

var (
	addr = ":2002"
)

type tcpHandler struct {
}

// 拿到请求的srcConn连接，执行逻辑 ，在这里 向请求的连接里写入数据
func (t *tcpHandler) ServeTCP(ctx context.Context, srcConn net.Conn) {
	srcConn.Write([]byte("tcpHandler"))
}

// tcp代理 支持负载均衡、中间件
func main() {
	lb := load_balance.LoadBanlanceFactory(load_balance.LbWeightRoundRobin) // 负载均衡器
	lb.Add("127.0.0.1:6001", "40")

	//构建路由及设置中间件
	counter, _ := public.NewFlowCountService("local_app", time.Second) // 限流服务 流量统计服务
	router := tcp_middleware.NewTcpSliceRouter()
	router.Group("/").Use(tcp_middleware.IpWhiteListMiddleWare(), tcp_middleware.FlowCountMiddleWare(counter)) //添加中间件，流量统计注入中间件

	//构建回调handler // 组装负载均衡器 和 router middleware中间
	routerHandler := tcp_middleware.NewTcpSliceRouterHandler(
		func(c *tcp_middleware.TcpSliceRouterContext) tcp_proxy.TCPHandler {
			return grpc_proxy.NewTcpLoadBalanceReverseProxy(c, lb) // 负载均衡和ctx上下文
		}, router)

	//启动服务。 tcp服务器和routerHandler 组合
	tcpServ := tcp_proxy.TcpServer{Addr: addr, Handler: routerHandler}
	fmt.Println("Starting tcp_proxy at " + addr)
	tcpServ.ListenAndServe()
}
